import React, { useState, useRef } from 'react'
// 导入请求购物车数据接口
import { getCarList } from '@/api/car'
import { useEffect, useMemo, useCallback } from 'react'
import { useSelector } from 'react-redux'
import { List, Image, Ellipsis, Stepper, Empty, SwipeAction, Dialog, Button, Checkbox } from 'antd-mobile'
import { updatecarnum, removecaritem, selectall, selectone } from '@/api/car'
import { SwipeActionRef } from 'antd-mobile/es/components/swipe-action'
import { Link } from 'react-router-dom'
import Navheader from '@/components/Navheader'

type carItemType = {
    cartid: string
    discount: number
    flag: boolean
    img1: string
    num: number
    originprice: number
    proid: string
    proname: string
    userid: string
}

export default function Car() {
    // const userid = useSelector((state: { userid: string }) => state.userid);
    const userid = useSelector((state: any) => state.counter.userid)
    console.log(userid);
    // 定义购物车数组
    const [carlistArr, setCarListArr] = useState<carItemType[]>([])
    const getcarlist = useCallback(() => {
        getCarList({ userid: userid }).then(res => {
            console.log('res', res);
            if (res.data.code == '10020') {
                // 说明购物车为空
                setCarListArr([])
            } else {
                // 购物车有数据
                setCarListArr(res.data.data)
                // 设置全选的状态
                //语法:const bool= arr.every(()=>{retuen 条件})
                const checked = res.data.data.every((item: carItemType) => item.flag)
                setCheckedAll(checked)
            }
        })
    }, [])

    useEffect(() => {
        // 初始化调用
        getcarlist()
    }, [])

    // 定义一个变量, 用来控制显示 空页面还是购物车的数据
    const emptyFlag = useMemo(() => {
        return carlistArr.length > 0 ? false : true
    }, [carlistArr])


    const ref = useRef<SwipeActionRef>(null)


    //定义购物车的全选状态
    const [checkedAll, setCheckedAll] = useState<boolean>(false)

    // 计算总价
    // const arr = [1, 2, 3, 4, 5];
    // let total = arr.reduce((sum, item) => {
    //     return sum += item
    // }, 0)
    // console.log(total);

    const totalprice = useMemo(() => {
        return carlistArr.reduce((sum, item) => {
            return item.flag ? sum += (item.originprice * item.num) : sum
        }, 0)
    }, [carlistArr])
    return (
        <div>
            {
                emptyFlag ? <Empty
                    style={{ padding: '64px 0' }}
                    imageStyle={{ width: 128 }}
                    description={
                        <div>
                            <p>购物车空空如也</p>
                            <Link to='/home'><Button color='danger'>加入购物车</Button></Link>
                        </div>
                    }
                /> :
                    <>
                        <Navheader title={`购物车${carlistArr.length}`} isshow={false}></Navheader>
                        <List>
                            {carlistArr.map(item => (
                                <SwipeAction
                                    key={item.cartid}
                                    ref={ref}
                                    closeOnAction={false}
                                    closeOnTouchOutside={true}
                                    rightActions={[
                                        {
                                            key: 'delete',
                                            text: '删除',
                                            color: 'danger',
                                            onClick: async () => {
                                                Dialog.confirm({
                                                    content: '确认要删除吗?',
                                                    onConfirm: async () => {
                                                        // 调用删除接口
                                                        removecaritem({ cartid: item.cartid }).then(res => {
                                                            // 删除成功, 重新更新购物车数据
                                                            if (res.data.code == 200) {
                                                                // 重新请求购物车数据
                                                                getcarlist()
                                                            }
                                                        })

                                                    },
                                                })
                                            },
                                        },
                                    ]}
                                >
                                    <List.Item
                                        prefix={
                                            <div style={{
                                                display: 'flex',
                                                justifyContent: "center",
                                                alignItems: 'center'
                                            }}>
                                                <div onClick={e => e.stopPropagation()}>
                                                    <Checkbox checked={item.flag} onChange={(val) => {
                                                        console.log(val);
                                                        // 调用单选接口
                                                        selectone({ cartid: item.cartid, flag: val }).then(res => {
                                                            console.log('res', res);
                                                            if (res.data.code == 200) {
                                                                // 重新请求购物车数据
                                                                getcarlist()
                                                            }
                                                        })

                                                    }} />
                                                </div>
                                                <Image
                                                    src={item.img1}
                                                    style={{ borderRadius: 20 }}
                                                    fit='cover'
                                                    width={80}
                                                    height={80}
                                                />
                                            </div>
                                        }
                                        description={
                                            <div>
                                                <Ellipsis direction='end' rows={2} content={item.proname} />
                                                <div style={{
                                                    display: 'flex',
                                                    justifyContent: "space-between"
                                                }}>
                                                    <span>{item.originprice}</span>
                                                    <Stepper
                                                        value={item.num}
                                                        onChange={value => {
                                                            console.log(value)
                                                            // 调用加入购物车的接口
                                                            updatecarnum({ cartid: item.cartid, num: value * 1 }).then(res => {
                                                                console.log('更新购物车', res);
                                                                if (res.data.code == 200) {
                                                                    // 重新请求购物车数据
                                                                    getcarlist()
                                                                }

                                                            })
                                                        }}
                                                    />
                                                </div>

                                            </div>
                                        }
                                    >

                                    </List.Item>
                                </SwipeAction>
                            ))}
                            {/* 底部的tabbar--权=全选-总价 */}
                            <div style={{
                                width: '100%',
                                height: '50px',
                                background: 'white',
                                display: 'flex',
                                justifyContent: "space-between",
                                position: "fixed",
                                bottom: 0,
                                left: 0
                            }}>
                                <div>
                                    <Checkbox checked={checkedAll} onChange={(val) => {
                                        // 调用全选事件
                                        selectall({ userid: userid, type: val }).then(res => {
                                            if (res.data.code == 200) {
                                                // 重新请求购物车数据
                                                getcarlist()
                                            }
                                        })
                                    }} />全选
                                </div>
                                <p>总价:{totalprice}元</p>
                                <Button color='danger'>合计</Button>
                            </div>
                        </List></>
            }


        </div>
    )
}